
package com.ifcar.app.activity.topic;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.CommonFrameActivity;
import com.ifcar.app.activity.NewsPage;
import com.ifcar.app.adapter.VoteViewBinder;
import com.ifcar.app.fragment.NRAbsPullLoadingListFrament;
import com.ifcar.app.model.Topic;
import com.ifcar.app.model.Vote;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.activity.R;

public class VoteFrament extends NRAbsPullLoadingListFrament implements OnClickListener, OnItemClickListener {
    private SimpleAdapter mAdapter;

    private List<Map<String, Object>> mData = new ArrayList<Map<String, Object>>();

    private List<Map<String, Object>> mAdatperData;
    
    private Map<String, Object> mFirstData;

    private View mHeaderLay;

    private VoteViewBinder mViewBinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRefreshTag(Topic.TOPIC_VOTE);

        if (savedInstanceState != null) {
            ArrayList<String> voteArray = savedInstanceState.getStringArrayList("voteArray");
            mData.addAll(Vote.stringArray2Data(voteArray));
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        ArrayList<String> voteArray = Vote.data2StringArray(mData);

        if (voteArray != null && voteArray.size() > 0) {
            outState.putStringArrayList("voteArray", voteArray);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        List<Map<String, Object>> data = getApplication().getVoteList();
        if (data != null) {
            getApplication().setVoteList(null);
            setData(data);
        }
    }   
    
    @Override
    public void onLoadingListViewAttached(LoadingListView loadingListView) {
        
        if (mHeaderLay == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            mHeaderLay = layoutInflater.inflate(R.layout.vote_list_item_header, null);

            FrameLayout extraContainer = (FrameLayout) mHeaderLay
                    .findViewById(R.id.vote_item_extra);

            View extra = layoutInflater.inflate(R.layout.more_layout, extraContainer, false);
            extraContainer.addView(extra);

            Button button = (Button) extra.findViewById(R.id.show_more_button);
            button.setOnClickListener(this);
        }
        if (mHeaderLay != null) {
            ListView listView = loadingListView.getListView();
            listView.addHeaderView(mHeaderLay, null, false);
        }
        super.onLoadingListViewAttached(loadingListView);
        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onLoadingListViewDetached(LoadingListView loadingListView) {
        super.onLoadingListViewDetached(loadingListView);
        if (mHeaderLay != null) {
            loadingListView.getListView().removeHeaderView(mHeaderLay);
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        goToGallery(arg2);
    }

    @Override
	public ListAdapter getAdapter() {
		return mAdapter;
	}

    @Override
    public boolean hasMoreView() {
        return false;
    }

    @Override
    public void onTabSelected(boolean first) {
        super.onTabSelected(first);
        if (first) {
            startLoading();
        }

        if (mViewBinder != null) {
            mViewBinder.setThread(Thread.currentThread());
            if (mHeaderLay != null) {
                Map<String, Object> data = mData != null && mData.size() > 0 ? mData.get(0) : null;
                if (data != null) {
                    mViewBinder.bindView(mHeaderLay, data, Vote.isVoted(getActivity(), data),
                            false, this);
                }
            }
        }

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onTabUnSelected() {
        super.onTabUnSelected();
        if (mViewBinder != null) {
            mViewBinder.setThread(null);
        }
        ListView listView = getListView();
        if (listView != null) {
            final int count = listView.getChildCount();
            for (int i = 0; i < count; i++) {
                ImageView img = (ImageView) listView.getChildAt(i).findViewById(R.id.img);
                if (img != null) {
                    img.setImageDrawable(null);
                }
            }
        }
    }

    @Override
    protected void onLoading() {
        super.onLoading();

        Message msg = getHandler().obtainMessage(MSG_LOADING);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        data.addAll(mData);
        msg.obj = data;
        getHandler().dispatchMessage(msg);
    }

    @Override
    protected void onHandleLoading(Object result) {
        super.onHandleLoading(result);
        List<Map<String, Object>> list = (List<Map<String, Object>>) result;
        setData(list);

        if (mAdapter != null && mAdapter.getCount() > 0) {
            if (isNeedRefresh()) {
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh();
                    }
                }, 200);
            }
        } else {
            refresh();
        }

    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(mAdapter == null);
        final Context context = getActivity();
        new Thread() {
            public void run() {
                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = Vote.getVoteList(context);
                getHandler().sendMessage(msg);
            };
        }.start();
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);
        List<Map<String, Object>> data = (List<Map<String, Object>>) result;

        if (data != null && data.size() != 0) {
            callLoadingListViewCompleteLoading(true, true);
            setData(data);
        } else {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }
    }

    private void setData(List<Map<String, Object>> data) {
        if (data != null && data.size() > 0) {
            mData.clear();
            mData.addAll(data);

            mFirstData = data.remove(0);

            mAdatperData = data;

            bindHeader();

            mAdapter = new SimpleAdapter(getActivity(), mAdatperData, R.layout.vote_list_item,
                    new String[] {
                            StringUtil.VOTE_QUESTION, StringUtil.VOTE_DATE,
                            StringUtil.VOTE_ITEM_LIST, StringUtil.VOTE_IMGSRC
                    }, new int[] {
                            R.id.question, R.id.date, R.id.num, R.id.img
                    });

            mAdapter.setViewBinder(mViewBinder);
            if (getListView() != null) {
                getListView().setAdapter(mAdapter);
            }
        }
    }
    
    private void bindHeader() {
        if (mHeaderLay == null || mFirstData == null) {
            return;
        }
        
        if (mViewBinder == null) {
            mViewBinder = new VoteViewBinder(getActivity());
        }

        if (inTabSelected()) {
            mViewBinder.setThread(Thread.currentThread());
        } else {
            mViewBinder.setThread(null);
        }

        boolean isVoted = Vote.isVoted(getActivity(), mFirstData);
        Button button = (Button) mHeaderLay.findViewById(R.id.show_more_button);
        button.setText(isVoted ? R.string.vote_see : R.string.vote_submit);

        mViewBinder.bindView(mHeaderLay, mFirstData, isVoted, false, this);
    }

    private void goToGallery(int position) {
        if (mData == null || mData.size() == 0 || position < 0 || position >= mData.size()) {
            return;
        }

        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        data.addAll(mData);
        getApplication().setVoteList(data);
        Bundle b = new Bundle();
        // position传过去,可以直接显示第几页
        b.putInt("position", position);
        Intent intent = CommonFrameActivity.getStartIntent(getActivity(),
                VoteGalleryFrament.class.getName(), VoteGalleryFrament.TAG, b);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_more_button:
                goToGallery(0);
                break;
            case R.id.digest_container: {
                Map<String, Object> data = (Map<String, Object>) v.getTag();
                String docid = (String) ModelUtils.getValue(data, StringUtil.VOTE_DOCID);
                if (!TextUtils.isEmpty(docid)) {
                    Intent itemintent = new Intent(getActivity(), NewsPage.class);
                    Bundle b = new Bundle();
                    b.putString(GetColumnsInfo.DOCID_TAG, docid);
                    b.putString(GetColumnsInfo.TID_TAG, "");
                    b.putString("position", "0");
                    b.putBoolean(GetColumnsInfo.HEADLINE_TAG, false);
                    b.putBoolean("isCollect", true);
                    itemintent.putExtras(b);
                    startActivity(itemintent);
                }
                break;
            }
            default:
                break;
        }

    }

    @Override
    public void onApplyTheme() {
        super.onApplyTheme();

        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Context context = getActivity();

        if (mHeaderLay != null) {     
            bindHeader();
            
            TextView lastVoteTitle = (TextView)mHeaderLay.findViewById(R.id.vote_last_title);
            themeSettingsHelper.setViewBackgroud(context, lastVoteTitle, R.drawable.vote_last_bg);
            themeSettingsHelper.setTextViewColor(context, lastVoteTitle, R.color.vote_last_title_color);
            
            Button button = (Button) mHeaderLay.findViewById(R.id.show_more_button);
            themeSettingsHelper.setViewBackgroud(context, button, R.drawable.netease_big_button);
            themeSettingsHelper.setTextViewColor(context, button, R.color.list_title_color);
        }

        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

}
